import axios from "axios";
import {message} from "ant-design-vue";
import {getToken, removeAuthInfo, EnumAlias} from "@/utils/common";
import router from "@/router";
import useAppStore from "@/store/app";
import {AES_Encrypt, getRandomString} from "@/utils/aes";

let isHaveTip = false;

if (import.meta.env.MODE == "development") {
  window.configGlobal = import.meta.env;
}

const http = axios.create({
  baseURL: window.configGlobal.VITE_APP_API_BASE,
  timeout: window.configGlobal.VITE_APP_API_TIMEOUT
});

//请求拦截
http.interceptors.request.use(
  (config: any) => {
    if (getToken()) {
      config.headers["Authorization"] = "Bearer " + getToken();
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

//响应拦截
http.interceptors.response.use(
  (response) => {
    let res = response.data;
    let code = res.code;
    let msg = res.message || "服务器开小车了~";
    if (res instanceof Blob) {
      return res;
    }
    if (code == 401) {
      //未登录
      if (!isHaveTip) {
        isHaveTip = true;
        message.error("登录已过期,请重新登录");
      }
      removeAuthInfo();
      router.push("/login").then((res) => {
        isHaveTip = false;
      });
      return Promise.reject(new Error(msg));
    }
    if (code !== 200) {
      message.error(msg);
      if (useAppStore.loading) useAppStore.loading = false; //全局取消加载中效果
      return Promise.reject(new Error(msg));
    }
    return res;
  },
  (error) => {
    if (useAppStore.loading) useAppStore.loading = false; //全局取消加载中效果
    // if(!axios.isCancel(error)){
    let msg = "";
    if (!error.response) {
      msg = "服务器开小车了~";
      message.error(msg);
      return Promise.reject(new Error(msg));
    }
    let status = error.response.status;
    if (error.response.data.message) {
      msg = msg + error.response.data.message + " ";
    }
    if (error.response.data.errMsg) {
      msg = msg + error.response.data.errMsg;
    }
    if (!error.response.data.msg && !error.response.data.errMsg) {
      msg = "服务器开小车了~";
    }
    message.error(msg);
    return Promise.reject(new Error(msg));
    // }else{
    //   return Promise.reject({});
    // }
  }
);

export default http;
